/**
 * 分页插件
 */
(function ($, window, document) {

    /**
     * 分页 pagination
     * @param { String } type - 分页类型，分为有刷新和无刷新，有刷新根据当前url规则读取pageSize和currentPage进行修改，无刷新则触发回调函数，返回页数，可选值：'refresh','ajax'
     * @param { Number } pageSize - 总页数
     * @param { Number } currentPage - 当前页数
     * @param { Number } sideNum - 当前页数左右各显示几条页数，默认为2
     * @param { Boolean } jumper - 是否显示跳转控制器，默认为false
     * @param { Boolean } showSize - 是否显示总页数，默认为false
     * @param { String } locale - 国际化语言，默认为'zh_CN'，可选值：'zh_CN','en_US','th_TH'
     * @param { Function } callback - 页数切换回调函数，返回当前页数
     */
    $.fn.pagination = function (options) {
        var self = this;

        var getQueryString = function (name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return window.unescape(r[2]);
            }
            return null;
        };
        var currentPage = getQueryString('currentPage') || 1;

        var settings = $.extend({
            type: 'refresh',
            pageSize: 1,
            currentPage: parseInt(currentPage),
            sideNum: 2,
            jumper: false,
            showSize: false,
            locale: 'zh_CN',
            callback: $.noop
        }, options);

        var getHref = function (pageSize, index) {
            var url = window.location.href;

            // 判断 url 是否带参数
            var urlReg = /pageSize=\d+/ig;

            if (urlReg.test(url)) {
                return url.replace(/(currentPage=)(\d+)/ig, function (url, $1) {
                    return $1 + index;
                });
            } else {
                return url + '?pageSize=' + pageSize + '&currentPage=' + index;
            }
        };

        var messages = {
            zh_CN: {
                goto: '到',
                pageClassifier: '页',
                confirm: '确定',
                total: '共',
            },
            en_US: {
                goto: 'Go to',
                pageClassifier: '',
                confirm: 'OK',
                total: 'Total '
            },
            th_TH: {
                goto: 'ไปที่',
                pageClassifier: '',
                confirm: 'ตกลง',
                total: 'ทั้งหมด '
            }
        }

        var getLocaleTxt = function (key) {
            return messages[settings.locale][key]
        }

        var htmlRender = function () {
            var html = '';
            if (settings.currentPage > 1) {
                if (settings.type === 'ajax') {
                    html += '<a class="jm-pagination-prev"><i class="jm-pagination-prev-arrow"></i></a>' +
                        '<a class="jm-pagination-num">1</a>';
                } else {
                    html += '<a class="jm-pagination-prev" href="' + getHref(settings.pageSize, settings.currentPage - 1) + '"><i class="jm-pagination-prev-arrow"></i></a>' +
                        '<a class="jm-pagination-num" href="' + getHref(settings.pageSize, 1) + '">1</a>';
                }
            } else {
                html += '<span class="jm-pagination-prev jm-pagination-disabled"><i class="jm-pagination-prev-arrow"></i></span>' +
                    '<span class="jm-pagination-num jm-pagination-num-active">1</span> ';
            }

            // 中间循环的起始页currentIndex和终止页loopNum
            var loopNum = settings.currentPage + settings.sideNum;
            var currentIndex = settings.currentPage - settings.sideNum;

            if (loopNum > settings.pageSize) {
                loopNum = settings.pageSize;
            }

            if (settings.currentPage - settings.sideNum <= 2) {
                currentIndex = 2;
            } else {
                html += '<span class="jm-pagination-dot">...</span>';
            }

            for (; currentIndex <= loopNum; currentIndex++) {
                if (currentIndex === settings.currentPage) {
                    html += '<span class="jm-pagination-num jm-pagination-num-active">' + settings.currentPage + '</span>';
                } else {
                    if (settings.type === 'ajax') {
                        html += '<a class="jm-pagination-num">' + currentIndex + '</a>';
                    } else {
                        html += '<a class="jm-pagination-num" href="' + getHref(settings.pageSize, currentIndex) + '">' + currentIndex + '</a>';
                    }
                }
            }

            if (loopNum < settings.pageSize - 1) {
                if (settings.type === 'ajax') {
                    html += '<span class="jm-pagination-dot">...</span>' +
                        '<a class="jm-pagination-num">' + settings.pageSize + '</a>';
                } else {
                    html += '<span class="jm-pagination-dot">...</span>' +
                        '<a class="jm-pagination-num" href="' + getHref(settings.pageSize, settings.pageSize) + '">' + settings.pageSize + '</a>';
                }

            } else if (loopNum == settings.pageSize - 1) {
                if (settings.type === 'ajax') {
                    html += '<a class="jm-pagination-num">' + settings.pageSize + '</a>';
                } else {
                    html += '<a class="jm-pagination-num" href="' + getHref(settings.pageSize, settings.pageSize) + '">' + settings.pageSize + '</a>';
                }
            }

            if (settings.currentPage < settings.pageSize) {
                if (settings.type === 'ajax') {
                    html += '<a class="jm-pagination-next"><i class="jm-pagination-next-arrow"></i></a>';
                } else {
                    html += '<a class="jm-pagination-next" href="' + getHref(settings.pageSize, settings.currentPage + 1) + '"><i class="jm-pagination-next-arrow"></i></a>';
                }
            } else {
                html += '<span class="jm-pagination-next jm-pagination-disabled"><i class="jm-pagination-next-arrow"></i></span>';
            }

            if (settings.jumper) {
                html += '<div class="jm-pagination-jumper">' +
                    '<span>' + getLocaleTxt('goto') + '</span>' +
                    '<input type="text" class="jm-pagination-input" />' +
                    '<span>' + getLocaleTxt('pageClassifier') + '</span>' +
                    '<button type="button" class="jm-pagination-btn">' + getLocaleTxt('confirm') + '</button>' +
                    '</div>';
            }

            if (settings.showSize) {
                html += '<span class="jm-pagination-total-page">' + getLocaleTxt('total') + settings.pageSize + getLocaleTxt('pageClassifier') + '</span>';
            }

            self.html(html);
        };

        htmlRender();

        // ajax 翻页的方式，绑定点击事件
        if (settings.type === 'ajax') {
            $(self).on('click', 'a.jm-pagination-prev', function () {
                settings.currentPage = settings.currentPage - 1;
                htmlRender();
                settings.callback.call(null, settings.currentPage);
            }).on('click', 'a.jm-pagination-num', function () {
                settings.currentPage = parseInt($(this).text());
                htmlRender();
                settings.callback.call(null, settings.currentPage);
            }).on('click', 'a.jm-pagination-next', function () {
                settings.currentPage = settings.currentPage + 1
                htmlRender();
                settings.callback.call(null, settings.currentPage);
            });
        }

        if (settings.jumper) {
            $(self).on('click', '.jm-pagination-btn', function () {
                var page = parseInt($(self).find('.jm-pagination-input').val());

                if (page && page <= settings.pageSize && page > 0) {
                    if (settings.type === 'ajax') {
                        settings.currentPage = page;
                        htmlRender();
                        $(self).find('.jm-pagination-input').val(page);
                        settings.callback.call(null, settings.currentPage);
                    } else {
                        window.location.href = getHref(settings.pageSize, page);
                    }
                }
            })
        }

        return {
            setPage: function(options) {
                settings.currentPage = options.currentPage || settings.currentPage;
                settings.pageSize = options.pageSize || settings.pageSize;
                htmlRender();
            },
            getCurrentPage: function() {
                return settings.currentPage
            }
        }
    }
})(jQuery, window, document);